//
//  WHomeMainViewController.swift
//  iiatn
//
//  Created by mnine on 18/4/5.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit

class WHomeMainViewController:  itBaseViewController , UIScrollViewDelegate{
    
    // 标签
    weak var titlesView = UIView()
    // 底部红色指示器
    weak var indicatorView = UIView()
    // 滚动视图
    weak var contentView = UIScrollView()
    // 当前选中的按钮
    weak var selectedButton = UIButton()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Slider_18x18_"), style: .plain, target: self, action: #selector(LeftBBClick))
        
        weak var weakSelf = self
        let vcl = WHomeViewController()
        let vcr = WNationTableViewController()
        vcl.title = "首页"
        vcr.title = "国别全览"
        weakSelf!.addChildViewController(vcl)
        weakSelf!.addChildViewController(vcr)
        if whaslogin! {
            print("Home had logan or register .")
        }else {
            NotificationCenter.default.addObserver(self, selector: #selector(notificationRegister), name: notifyNameMsgRecv, object: nil)
            let res = WRegisterSViewController()
            res.title = "注册"
            weakSelf!.addChildViewController(res)
        }
        //设置顶部标签栏
        weakSelf!.setupTitlesView()
        // 底部的scrollview
        weakSelf!.setupContentView()
    }
    
    /// 顶部标签栏
    func setupTitlesView() {
        // 顶部背景
        let bgView = UIView()
        bgView.frame = CGRect(x: 0, y: kTitlesViewY, width: SCREENW, height: kTitlesViewH)
        view.addSubview(bgView)
        // 标签
        let titlesView = UIView()
        titlesView.backgroundColor = WGlobalColor()
        titlesView.frame = CGRect(x: 0, y: 0, width: SCREENW, height: kTitlesViewH)
        bgView.addSubview(titlesView)
        self.titlesView = titlesView
        //底部红色指示器
        let indicatorView = UIView()
        indicatorView.backgroundColor = WGlobalRedColor()
        indicatorView.height = kIndicatorViewH
        indicatorView.y = kTitlesViewH - kIndicatorViewH
        indicatorView.tag = -1
        self.indicatorView = indicatorView
        
        //内部子标签
        let count = childViewControllers.count
        let width = titlesView.width / CGFloat(count)
        let height = titlesView.height
        
        for index in 0..<count {
            let button = UIButton()
            button.height = height
            button.width = width
            button.x = CGFloat(index) * width
            button.tag = index
            let vc = childViewControllers[index]
            button.titleLabel!.font = UIFont.systemFont(ofSize: 14)
            button.setTitle(vc.title!, for: .normal)
            button.setTitleColor(UIColor.gray, for: .normal)
            button.setTitleColor(WGlobalRedColor(), for: .disabled)
            button.addTarget(self, action: #selector(titlesClick), for: .touchUpInside)
            titlesView.addSubview(button)
            //默认点击了第一个按钮
            if index == 0 {
                button.isEnabled = false
                selectedButton = button
                //让按钮内部的Label根据文字来计算内容
                button.titleLabel?.sizeToFit()
                indicatorView.width = button.titleLabel!.width
                indicatorView.centerX = button.centerX
            }
        }
        //底部红色指示器
        titlesView.addSubview(indicatorView)
    }
    
    /// 标签上的按钮点击
    func titlesClick(button: UIButton) {
        // 修改按钮状态
        selectedButton!.isEnabled = true
        button.isEnabled = false
        selectedButton = button
        // 让标签执行动画
        UIView.animate(withDuration: kAnimationDuration) {
            self.indicatorView!.width = self.selectedButton!.titleLabel!.width
            self.indicatorView!.centerX = self.selectedButton!.centerX
        }
        //滚动,切换子控制器
        var offset = contentView!.contentOffset
        offset.x = CGFloat(button.tag) * contentView!.width
        contentView!.setContentOffset(offset, animated: true)
    }
    
    /// 底部的scrollview
    func setupContentView() {
        //不要自动调整inset
        automaticallyAdjustsScrollViewInsets = false
        
        let contentView = UIScrollView()
        contentView.frame = view.bounds
        contentView.delegate = self
        contentView.contentSize = CGSize(width: contentView.width * CGFloat(childViewControllers.count), height: 10)
        contentView.isPagingEnabled = true
        view.insertSubview(contentView, at: 0)
        // 内容
        contentView.frame = CGRect(x: 5, y: 0, width: SCREENW-10, height: SCREENH)
        self.contentView = contentView
        //添加第一个控制器的view
        scrollViewDidEndScrollingAnimation(contentView)
    }
    
    // MARK: - UIScrollViewDelegate
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        // 添加子控制器的 view
        // 当前索引
        let index = Int(scrollView.contentOffset.x / scrollView.width)
        // 取出子控制器
        let vc = childViewControllers[index]
        vc.view.x = scrollView.contentOffset.x
        vc.view.y = 0 // 设置控制器的y值为0(默认为20)
        //设置控制器的view的height值为整个屏幕的高度（默认是比屏幕少20）
        vc.view.height = scrollView.height
        scrollView.addSubview(vc.view)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScrollingAnimation(scrollView)
        // 当前索引
        let index = Int(scrollView.contentOffset.x / scrollView.width)
        // 点击 Button
        let button = titlesView!.subviews[index] as! UIButton
        titlesClick(button: button)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 缺个广播（登录后 手机注册忘密 邮箱注册忘密后） 使得注册controller隐藏
    func notificationRegister(){
        if (self.titlesView?.subviews)!.count > 3 && !whaslogin! {
            (self.titlesView?.subviews)![2].isHidden = true
            //内部子标签
            let count = 2
            let width = (self.titlesView?.width)! / CGFloat(count)
            for index in 0..<count {
                (self.titlesView?.subviews)![index].width = width
                (self.titlesView?.subviews)![index].x = CGFloat(index) * width
            }
            self.titlesClick(button: (self.titlesView?.subviews)![0] as! UIButton)
        }
    }
}
